package com.zanbo.hot100.reverse_nodes_in_k_group;

import com.zanbo.structure.data.ListNode;
import com.zanbo.structure.utils.ListNodeUtil;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;

/**
 * @author zanbo
 * @program Solution
 * @since 2021-12-23 下午 4:08
 */
public class Reverse_nodes_in_k_group {
    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode listNode = solution.reverseKGroup(ListNodeUtil.getListNode(), 3);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
}

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        Deque<ListNode> stack = new ArrayDeque<ListNode>();
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        while (true) {
            int count = 0;
            ListNode tmp = head;
            while (tmp != null && count < k) {
                stack.add(tmp);
                tmp = tmp.next;
                count++;
            }
            if (count != k) {
                p.next = head;
                break;
            }
            while (!stack.isEmpty()){
                p.next = stack.pollLast();
                p = p.next;
            }
            p.next = tmp;
            head = tmp;
        }
        return dummy.next;
    }
}